const puppeteer = require("puppeteer");
const path      = require("path");
const config    = require('../config/config');
const utils     = require('../util/utils');
const fileUtil  = require('../util/file_util');
const fs        = require('fs');
const myRequest = require('request');

//搜索页
const searchUrl              = 'keyword_engine/get_related_keywords';
//工具箱---销量预估---计算月销量
const salesSearchUrl         = 'api/sales_estimator';
//选品功能---潜力市场搜索器
const listingSearchUrl       = 'api/listing_grader';
//选品功能 --- 选品数据库---产品搜索
const searchProducts         = 'https://api.junglescout.com/api/products/get_products?data';
//选品功能---市场潜力搜索器---关键字搜索
const searchListingKeywords  = 'https://api.junglescout.com/api/keywords/get_keywords?data';

//黑名单网址
const blackList = [
    'https://members.junglescout.cn/#/account',
    'https://members.junglescout.cn/#/account/info',
    'https://members.junglescout.cn/#/account/billing',
    'https://members.junglescout.cn/#/account/subscriptions',
    'https://members.junglescout.cn/#/account/email-settings',
    'https://members.junglescout.cn/#/account/alert-settings',
    'https://members.junglescout.cn/#/account/languages'

];

const searchProductsType = 10;
const searchListingKeywordsType = 20;

const searchDefaultNotice = '输入关键词或ASIN';
const salesDefaultNotice = '计算月销量';
const listingDefaultNotice = '搜索';

class Junglescout {

    constructor(options) {
        if(!Junglescout.single){
            this.windowOptions = [
                '--disable-web-security', //解决跨域问题
                `--disable-extensions-except=${options.wyfyPluginPath},${options.googlePluginPath},${options.proxyPath}`,
                `--load-extension=${options.wyfyPluginPath},${options.googlePluginPath},${options.proxyPath}`,
                // `--proxy-server=http://${config.PROXY.HOST}:${config.PROXY.PORT}`,
                `–default-browser-check` //不检查默认浏览器
            ];
            this.browser = null;
            this.page = null;
            this.targetUrl = options.targetUrl;
            this.timeOptions = { waitUntil: ["domcontentloaded"] };
            this.closeFn = options.closeFn;
            this.username = options.username;
            this.expireTime = options.expireTime;
            this.productId = options.productId;
            this.clientToken = options.clientToken;
            this.monitorTimers = [];
            this.decode = options.decode;
            //关键字功能 > 关键字搜索和反查
            this.searchTime = null;
            //工具箱---销量预估---计算月销量
            this.salesSearchTime = null;
            //工具箱---listing评分器---搜索
            this.listingSearchTime = null;
            this.disabled = true;
            this.salesDisabled = true;
            this.listingDisabled = true;
            this.token = options.token;
            this.bookmarkPath = options.bookmarkPath;
            this.client = null;
            Junglescout.single = this;
        }
        return Junglescout.single;
    }

    async loadWindow(){
        if(this.browser){
            await this.browser.newPage();
            return;
        }
        this.browser = await puppeteer.launch({
            headless: false,
            ignoreHTTPSErrors: true,
            // credentialsEnableService:false,
            // passwordManagerEnabled:false,
            ignoreDefaultArgs: ['--enable-automation','--disable-extensions'],
            defaultViewport: {
                width: 0,
                height: 0
            },
            args: this.windowOptions,
            // userDataDir: this.bookmarkPath,
        });
        this.page = await this.browser.newPage();
        this.client = this.page._client;
        console.log(`上下文初始完毕`);
        //关闭起始页的page
        await this.closeFirstPage();

        //开启拦截器
        await this.openPageInterception(this.page);
        await this.camouflageBrowser();
        await this.intercept();

        await this.addCookies('members.junglescout.com');
        await this.goPage(this.targetUrl);
        console.log(`打开页面成功`);
        //页面加载完毕后的后置操作
        await this.after();

        // await this.closeWindows();
    }

    async addCookies(domain){
        let cookie = 'optimizelyEndUserId=oeu1600741535219r0.6344778130073587; _vwo_uuid_v2=D31CE1AFB7AEEA2B9AF7B74123DD8E21F|2cd52520e0288d898408dc702c6ac6c7; __zlcmid=10JjSC6lHzs3CGG; __stripe_mid=f2b2eb5d-fad9-4520-ba23-45b93b395c3e8e3ede; _hjid=2c3d74b6-5826-4382-a8c8-1ccb6b2b4a90; _ga=GA1.3.1756808790.1600741536; __ssid=67d0e7ccd9d0752357f2f748ab5484e; _omappvp=Zlr8w4VTEBELBtcFapZBoe3ETqwUuYvhyAlaFKlkpx1CH9HBMyLbfAIcwAb2k0ULREzB0ZYp5MrvkOveMfLc8UNCmk5POo9I; _fbp=fb.1.1600918797451.101308569; _rdt_uuid=1600918798810.472dfeeb-c990-49bb-8f52-7033c10c91aa; _pin_unauth=dWlkPU5HUmtZVEU1TVdFdFlURXpNUzAwWW1RMUxUZ3pPVEF0WXpSak5tVmxNVFZtTkRNeg; _vwo_uuid_v2=D31CE1AFB7AEEA2B9AF7B74123DD8E21F|2cd52520e0288d898408dc702c6ac6c7; _vis_opt_test_cookie=1; _vis_opt_s=1%7C; _gcl_au=1.1.2122107006.1615298775; _rdt_uuid=1600918798810.472dfeeb-c990-49bb-8f52-7033c10c91aa; _hjTLDTest=1; userId=631935; js-fullstory=true; userEmail=gth313@163.com; membershipType=Web App Pro Monthly; extensionType=None; __cfduid=da87d0512496f5c3721cf297b2ed191e81615342258; ajs_anonymous_id=%2255d60c14-f610-42de-91d3-0db38f17a011%22; _gid=GA1.3.206894639.1615465436; _gid=GA1.2.206894639.1615465436; auth_token=eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTYwNzAzMDYsImlhdCI6MTYxNTQ2NTUwNiwiaXNzIjoianVuZ2xlc2NvdXRfYXBpIiwiYXVkIjoiY2xpZW50IiwiYXV0aF90b2tlbiI6IjkwY2E4NTg0MmNhMTc5YmM2N2VjOTgzYWQzNTBmYmFmIn0.T8HWnyani1tZ20KIlC1KZRePCuWVExa35sPTydP-DHA; ajs_user_id=631935; _hjIncludedInSessionSample=1; _hjAbsoluteSessionInProgress=0; __stripe_sid=2fbb67fb-cdcb-4e92-a46d-cf47f3c1f49694a1a3; mp_c74f4284138a8d26cd2c3b5ebba43d0f_mixpanel=%7B%22distinct_id%22%3A%20%22178213e4d64bb2-096d5640179497-930346c-1fa400-178213e4d65b51%22%2C%22%24device_id%22%3A%20%22178213e4d64bb2-096d5640179497-930346c-1fa400-178213e4d65b51%22%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fwww.junglescout.com%2F%22%2C%22%24initial_referring_domain%22%3A%20%22www.junglescout.com%22%7D; _uetsid=a55d0200826411eba00e9510c0ad5797; _uetvid=a55d5ec0826411eb866583bddf867973; _ga_9C02FJRLCF=GS1.1.1615468460.6.1.1615469276.0; _ga=GA1.2.1756808790.1600741536; _dd_s=rum=0&expire=1615470490253';
        let cookies = cookie.split(';').map(
            pair => {
                let name = pair.trim().slice(0, pair.trim().indexOf('='));
                let value = pair.trim().slice(pair.trim().indexOf('=') + 1);
                return {name, value, domain}
            });
        console.log(`Cookies => ${JSON.stringify(cookies)}`);
        await Promise.all(cookies.map(pair => {
            return this.page.setCookie(pair)
        }))
    }

    async openPageInterception(page){
        page.setRequestInterception(true);
    }

    async after(){
        //新page监听
        await this.monitorTimer();
        //注入js
        await this.injectScript();
    }


    async injectScript(){
        //禁用敏感组件
        await this.disableAssembly()

        await this.eventMonitor();
    }

    async disableAssembly(){
        //右下角消息提示
        let monitorMsgTimer = setInterval(async () => {
            try {
                let msg = await this.page.$('#pendo-image-wrapper-62e6c736');
                await this.page.evaluate((els, value) => {
                        els.setAttribute('style', value)
                    },
                    msg,
                    'display:none'
                );
            }catch (e) {
            }
        },500);

        //账户设置
        let accountTimer = setInterval(async () => {
            try {
                let account = await this.page.$('#root > div > div.app > div.NavbarWrapper-wuhdp-0.StyledNavbarWrapper-mhfjmp-0.evoPNG > div > div.NavbarLink-mhfjmp-2.egxwJp.navbar-link-account > div > div.AccountInfo-ixx03q-10.bqxCFe');
                if(!account){
                    return;
                }
                await this.page.evaluate((els, value) => {
                        els.setAttribute('style', value)
                    },
                    account,
                    'display:none'
                );
            }catch (e) {
            }
        },500);

        //账户设置旁边铃声
        let systemMessageTimer = setInterval(async () => {
            //
            try {
                let systemMessage = await this.page.$('#root > div > div.app > div.NavbarWrapper-wuhdp-0.StyledNavbarWrapper-mhfjmp-0.evoPNG > div > div:nth-child(1) > div > span');
                if(!systemMessage){
                    return;
                }
                await this.page.evaluate((els, value) => {
                        els.setAttribute('style', value)
                    },
                    systemMessage,
                    'display:none'
                );
            }catch (e) {
            }
        },500);

        //竞品添加按钮
        let commentGoodsAddButton = setInterval(async () => {
            let dom = '#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.tracker__groups > div.CardWrapper-sc-1xay5eh-0.dNJhwz.card-section > div > button';
            let addButton = await this.page.$(dom);
            if(!addButton){
                return;
            }
            // await this.page.evaluate((els, value) => {
            //         // els.setAttribute('style',value);
            //     },
            //     addButton,
            //     'display:none'
            // );

        })

        //选品功能 - 潜力市场搜索器
        let potentialTimer = setInterval(async () => {

            try {
                let potential1Message = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.filters.filters--keyword > div.CardWrapper-sc-1xay5eh-0.hKcJYh.card-section.Header-sc-1sk6owh-0.hgiTlS > div > button:nth-child(2)');
                let potential2Message = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.filters.filters--keyword > div.CardWrapper-sc-1xay5eh-0.hKcJYh.card-section.Header-sc-1sk6owh-0.hgiTlS > div > button:nth-child(3)');
                let potential3Message = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.filters.filters--database > div.CardWrapper-sc-1xay5eh-0.hKcJYh.card-section.Header-sc-1sk6owh-0.hgiTlS > div > button:nth-child(1)');
                let potential4Message = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.filters.filters--database > div.CardWrapper-sc-1xay5eh-0.hKcJYh.card-section.Header-sc-1sk6owh-0.hgiTlS > div > button:nth-child(2)');
                if(potential1Message){
                    await this.page.evaluate((els, value) => {
                            els.setAttribute('style', value)
                        },
                        potential1Message,
                        'display:none'
                    );
                }
                if(potential2Message){
                    await this.page.evaluate((els, value) => {
                            els.setAttribute('style', value)
                        },
                        potential2Message,
                        'display:none'
                    );
                }

                if(potential3Message){
                    await this.page.evaluate((els, value) => {
                            els.setAttribute('style', value)
                        },
                        potential3Message,
                        'display:none'
                    );
                }

                if(potential4Message){
                    await this.page.evaluate((els, value) => {
                            els.setAttribute('style', value)
                        },
                        potential4Message,
                        'display:none'
                    );
                }

            }catch (e) {
            }
        },500);
        this.monitorTimers.push(monitorMsgTimer);
        this.monitorTimers.push(accountTimer);
        this.monitorTimers.push(systemMessageTimer);
        this.monitorTimers.push(potentialTimer);
        this.monitorTimers.push(commentGoodsAddButton);
    }


    async monitorTimer(){
        //监听新页面
        let newPageTimer = setInterval(async () => {
            try {
                let pageCache = await this.browser.pages();
                for (let i=0;i<pageCache.length;i++){
                    let otherPage = pageCache[i];
                    let url = otherPage.url()
                    if(url.indexOf(this.targetUrl) !== -1 || url.indexOf('chrome://settings') !== -1){
                        if(otherPage != this.page){
                            //如果打开了多个魔词界面 强制关闭
                            console.log(`close a page..  ${pageCache[i].url()}`)
                            // await otherPage.close();
                        }
                    }
                    if(blackList.indexOf(url) !== -1){
                        await otherPage.close();
                    }
                }
                pageCache = await this.browser.pages();
                if(pageCache.length === 0){
                    await this.closeWindows();
                }
            } catch (e) {

            }
        },500);

        let searchTimer = setInterval(async () => {
            if(!this.searchTime){
                return;
            }
            this.disabled = await this.searchHandler(this.searchTime,15000,this.displaySearchButton);
        },1000);

        // let listingSearchTimer = setInterval(async () => {
        //     if(!this.listingSearchTime){
        //         return;
        //     }
        //     this.listingDisabled = await this.searchHandler(this.listingSearchTime,30000,this.displayListingSearchButton);
        // },1000);

        let salesSearchTimer = setInterval(async () => {
            if(!this.salesSearchTime){
                return;
            }
            this.salesDisabled = await this.searchHandler(this.salesSearchTime,30000,this.displaySalesSearch);
        },1000);
        //
        let lintingKeywordsSearchTimer = setInterval(async () => {
            let data = await this.getCustomCount(searchListingKeywordsType).catch((err) => {
                console.log(`Time out netWork. err:${err}`)
                return Promise.resolve(null)
            });
            if(!data){
                return;
            }
            await this.displayListingKeywordsSearch(`搜索-使用次数(${data.usedCount}/${data.totalCount})`);
        },1000);

        // let searchProductsSearchTimer = setInterval(async () => {
        //     let data = await this.getCustomCount(searchProductsType);
        //     if(!data){
        //         return;
        //     }
        //     await this.displaySearchProductsSearch(`搜索-使用次数(${data.usedCount}/${data.totalCount})`);
        // },1000);
        this.monitorTimers.push(newPageTimer);
        this.monitorTimers.push(searchTimer);
        this.monitorTimers.push(salesSearchTimer);
        this.monitorTimers.push(lintingKeywordsSearchTimer);
        // this.monitorTimers.push(searchProductsSearchTimer);
    }

    async searchHandler(searchTime,intervalTime,functionName){
        //计算时间间隔
        let currentTime = new Date().getTime();
        let downTime = currentTime - searchTime;
        if(downTime < intervalTime){
            let t = Math.ceil((intervalTime - downTime) / 1000);
            console.log(`超出限制 ${t}S后执行`)
            await functionName.call(this,(`${t}秒后搜索`));
            return false;
        }
        await functionName.call(this);
        return true;
    }

    async searchTips(request){
        request.respond({
            status: 200,
            contentType: 'text/html;charset=UTF-8',
            headers:{
                'X-custom-sing':'yes',
                'Access-Control-Allow-Origin':'*'
            },
            body: '\n' +
                '<html>\n' +
                '<head><title>提示</title></head>\n' +
                '<body>\n' +
                '<center><h1>搜索频繁,请稍后再试</h1></center>\n' +
                '<hr><center><h3><a href="https://www.merchantwords.com">回首页</a></h3></center>\n' +
                '</body>\n' +
                '</html>\n'
        });

    }

    async salesTips(request){
        request.respond({
            status: 200,
            contentType: 'application/json; charset=utf-8',
            headers:{
                'Access-Control-Allow-Origin':'*',
                'X-custom-sing':'yes'
            },
            body:JSON.stringify({
                data:{
                    estSalesResult:'歇一歇~',
                    message:'稍后重试',
                    status:true
                },
                message:''
            })
        })
    }

    async responseData(request,contentType,body,statusCode){
        request.respond({
            status: statusCode,
            contentType: contentType,
            headers:{
                'Access-Control-Allow-Origin':'*',
                'X-custom-sing':'yes'
            },
            body:JSON.stringify(body)
        })
    }

    async listingTips(request){
        request.respond({
            status: 200,
            contentType: 'application/json; charset=utf-8',
            headers:{
                'Access-Control-Allow-Origin':'*',
                'X-custom-sing':'yes'
            },
            body:JSON.stringify({
                "data": {
                    "scores": {
                        "title": {
                            "value": 157,
                            "score": 20,
                            "tips": "Sweeeet! You have created a nice length Product Title."
                        },
                        "description": {
                            "value": 749,
                            "score": 5,
                            "tips": "You can improve your searchability in the Amazon algorithm if you include more text in Product Description. Additionally, this will help your customers understand why they need to buy your product immediately. You may see increased impressions and conversion rate if you let Amazon and your customers know more about your product."
                        },
                        "images": {
                            "value": [
                                {
                                    "HiResImage": {
                                        "URL": "https://images-na.ssl-images-amazon.com/images/I/51Q8yp%2B0zPL._AC_SL1039_.jpg",
                                        "Height": {
                                            "_": "1039"
                                        },
                                        "Width": {
                                            "_": "1039"
                                        }
                                    }
                                },
                                {
                                    "HiResImage": {
                                        "URL": "https://images-na.ssl-images-amazon.com/images/I/81Oo%2BU3xAAL._AC_SL1500_.jpg",
                                        "Height": {
                                            "_": "1500"
                                        },
                                        "Width": {
                                            "_": "1500"
                                        }
                                    }
                                },
                                {
                                    "HiResImage": {
                                        "URL": "https://images-na.ssl-images-amazon.com/images/I/810YPlGOKHL._AC_SL1500_.jpg",
                                        "Height": {
                                            "_": "1500"
                                        },
                                        "Width": {
                                            "_": "1500"
                                        }
                                    }
                                },
                                {
                                    "HiResImage": {
                                        "URL": "https://images-na.ssl-images-amazon.com/images/I/81IIIlMerML._AC_SL1500_.jpg",
                                        "Height": {
                                            "_": "1500"
                                        },
                                        "Width": {
                                            "_": "1500"
                                        }
                                    }
                                },
                                {

                                },
                                {
                                    "HiResImage": {
                                        "URL": "https://images-na.ssl-images-amazon.com/images/I/81bGGL9PgQL._AC_SL1500_.jpg",
                                        "Height": {
                                            "_": "1500"
                                        },
                                        "Width": {
                                            "_": "1500"
                                        }
                                    }
                                },
                                {
                                    "HiResImage": {
                                        "URL": "https://images-na.ssl-images-amazon.com/images/I/71oGd3qzENL._AC_SL1280_.jpg",
                                        "Height": {
                                            "_": "1280"
                                        },
                                        "Width": {
                                            "_": "1280"
                                        }
                                    }
                                }
                            ],
                            "score": 6,
                            "highRes": 6,
                            "tips": "This is a good start, but you can still add more product images. Maybe a different angle of your product, a 'lifestyle' shot of your product in action."
                        },
                        "bullets": {
                            "value": [
                                "★ THE PERFECT BRUSH TO GET ALL NASTY MATS OUT OF YOUR PET’S FUR – Hertzko’s Slicker Brush gently removes Loose Hair, and eliminates Tangles, Knots, Dander and trapped Dirt. WORKS GREAT ON DOGS AND CATS WITH ALL SIZES AND HAIR TYPES!",
                                "★ GET RID OF MATS WITHOUT HURTING HER - The bristles are FINE bent wires designed to penetrate DEEP into the coat and is really able to groom the undercoat well without scratching your pet's skin!",
                                "★ EASY TO CLEAN – When you’re done brushing your pet, Simply click the button and the bristles retract back into the brush, Making is SUPER SIMPLE to remove all the hair from the brush, So it’s ready for the next time use.",
                                "★ YOUR PET WILL NOT ONLY ‘LOOK’ GOOD BUT ‘FEEL' GREAT TOO! – Our brush Grooms and massages for a healthy coat, increasing blood circulation and leaves your pet’s coat soft and shiny. Your Pet will love being brushed !",
                                "★ COMFORTABLE, STRONG, AND DURABLE- Our Slicker Brush is especially designed with a COMFORT-GRIP and ANTI-SLIP HANDLE, which prevents hand and wrist strain no matter how long you brush your pet !"
                            ],
                            "data": {
                                "optimized": false,
                                "size": 1062
                            },
                            "score": 20,
                            "tips": "Thumbs up, you’ve taken advantage of this opportunity to include key features to help sell your product. Quick tip: sellers may not have time to read everything, so put your most important Key Features at the top to have the greatest chance that it gets read!"
                        },
                        "reviews": {
                            "value": 38209,
                            "score": 25,
                            "tips": "Nicely done, you have gathered a lot of reviews. How does this stack up in your niche? It depends on the competitiveness of your niche, but keep doing what you’re doing because Amazon sellers will continue gathering more reviews!"
                        },
                        "rating": {
                            "value": 4.5,
                            "score": 20,
                            "tips": "Excellent! Looks like customers think the world of your product. Keep it up!"
                        }
                    },
                    "totalScore": 96,
                    "convertedScore": "Optimized Listing",
                    "convertedInAppScore": "搜索太快啦~ 稍后再试吧",
                    "product": {
                        "title": "Hertzko Self Cleaning Slicker Brush – Gently Removes Loose Undercoat, Mats and Tangled Hair – Your Dog or Cat Will Love Being Brushed with The Grooming Brush",
                        "imageUrl": "https://images-na.ssl-images-amazon.com/images/I/41wzgc0dDzL._AC_US75_.jpg"
                    }
                },
                "message": null
            })
        })
    }

    /**
     * 关闭浏览器
     * @returns {Promise<void>}
     */
    async closeWindows(){
        this.closeFn && this.closeFn();
        let pages = await this.browser.pages();
        await this.monitorTimers.forEach(item => clearInterval(item));
        await pages.forEach(item => item.close());
        await this.browser.close();
        this.browser = null;
        Junglescout.single = null;
    }

    /**
     * 访问页面
     * @param url
     * @returns {Promise<void>}
     */
    async goPage(url){
        //打开页面
        await this.page.goto('https://members.junglescout.com/#/keyword',this.timeOptions);
    }

    async closeFirstPage(){
        let pages = await this.browser.pages();
        if(!pages || pages.length === 0){
            return;
        }
        await pages[0].close();
    }
    //
    // async addCookies(domain){
    //     if(!this.cookie || '' === this.cookie){
    //         return;
    //     }
    //     let cookies = this.cookie.split(';').map(
    //         pair => {
    //             let name = pair.trim().slice(0, pair.trim().indexOf('='));
    //             let value = pair.trim().slice(pair.trim().indexOf('=') + 1);
    //             return {name, value, domain}
    //         });
    //     await Promise.all(cookies.map(pair => {
    //         return this.page.setCookie(pair)
    //     }))
    // }

    async camouflageBrowser(){
        //删掉webdriver属性 以免被检测出为无头浏览器
        await this.page.evaluateOnNewDocument(() => {
            const newProto = navigator.__proto__;
            delete newProto.webdriver;
            navigator.__proto__ = newProto;
        });

        //无头浏览器模式下,全局对象下的chrome对象是没有 runtime属性的
        await this.page.evaluateOnNewDocument(() => {
            window.navigator.chrome = {
                runtime: {}
            };
        });
    }

    async intercept() {

        this.browser.on('targetcreated', async (target) => {
            if (target.type() === 'page') {
                let page = await target.page();
                let title = await page.title();
                await this.openPageInterception(page);
                await this.registerPageRequestEvent(page);
                this.registerPageResponseEvent(page);
                await page.reload(true);
            }
        });

        this.page.once('close',async () => {
            await this.closeWindows();
        });

        //开启请求拦截
        this.registerPageRequestEvent(this.page);
        this.registerPageResponseEvent(this.page);
    }


    async registerPageResponseEvent(page){
        page.on('response',async (response) => {
            let url = response.url();
            let type = utils.getUrlType(url);
            if(utils.matchStaticSourceUrl(url)){
                let source = await response.text();
                let buffer = await response.buffer();
                //写入资源到本地缓存,提供访问性能
                let filePath = `${global.baseResourcePath}\\cache\\${utils.md5Crypto(url)}.${type}`;
                if(response.request().resourceType() === 'image'){
                    fileUtil.writeFile(filePath,buffer);
                }else{
                    fileUtil.writeFile(filePath,source);
                }
            }

            if(await this.isOptionsResponse(response)){
                return;
            }
            if(response.url().indexOf(searchUrl) !== -1){
                if(this.disabled){
                    this.searchTime = new Date().getTime();
                }
            }
            // if(response.url().indexOf(salesSearchUrl) !== -1){
            //     if(this.salesDisabled){
            //         this.salesSearchTime = new Date().getTime();
            //     }
            // }
            // if(response.url().indexOf(listingSearchUrl) !== -1){
            //     if(this.listingDisabled){
            //         this.listingSearchTime = new Date().getTime();
            //     }
            // }
            if(await this.getSearchProductUrlPrefix(response.url())){
                console.log(`getSearchProductUrlPrefix:${response.url()}`);
                let data = await this.addUseCount(searchProductsType).catch((err) => {
                    console.log(`Time out netWork. err:${err}`)
                    return Promise.resolve(null)
                });
                if(!data){
                    return;
                }
                await this.displaySearchProductsSearch(`搜索-使用次数(${data.usedCount}/${data.totalCount})`);
                console.log(`Add one count. Type:[${searchProductsType}]`)
            }

            if(await this.getSearchListingUrlPrefix(response.url())){
                console.log(`getSearchListingUrlPrefix:${response.url()}`);
                let data = await this.addUseCount(searchListingKeywordsType).catch((error) => {
                    console.log(`Time out netWork. err:${error}`)
                    return Promise.resolve(null)
                });
                if(!data){
                    return;
                }
                await this.displaySearchProductsSearch(`搜索-使用次数(${data.usedCount}/${data.totalCount})`);
                console.log(`Add one count. Type:[${searchListingKeywordsType}]`)
            }
        });
    }

    async registerPageRequestEvent(page){
        page.on('request',async (request) => {
            let url = request.url();
            let type = utils.getUrlType(url);
            console.log(`request :${url} type:${type}`);
            // 如果是静态资源文件,从缓存获取并返回
            if(utils.matchStaticSourceUrl(url)){
                let path = `${global.baseResourcePath}\\cache\\${utils.md5Crypto(url)}.${type}`;
                if((await fileUtil.exists(path))){
                    request.respond({
                        status:200,
                        contentType:utils.getUrlContentType(url),
                        body:fs.readFileSync(path)
                    });
                    return;
                }
            }
            if(url.indexOf(searchUrl) !== -1){
                console.info(`➞ Search: ${url}`);
                let isOptions = await this.isOptionRequest(request);
                if(!isOptions){
                    if(!this.disabled){
                        await this.searchTips(request);
                        return;
                    }
                }
            }
            // if(url.indexOf(salesSearchUrl) !== -1){
            //     console.info(`➞ SalesSearchUrl: ${url}`);
            //     let isOptions = await this.isOptionRequest(request);
            //     if(!isOptions){
            //         if(!this.salesDisabled){
            //             await this.salesTips(request);
            //             return;
            //         }
            //     }
            // }

            if(url === 'https://api.junglescout.com/api/product_tracks/create_from_web_app_bulk'){
                let body = {"error":["暂未开放"]};
                await this.responseData(request,'application/json; charset=utf-8',body,500);
                return;
            }

            // if(await this.getSearchProductUrlPrefix(url)){
            //     console.log(`➞ Search Products:${url}`);
            //     if(!await this.checkUsedCount(searchProductsType)){
            //         await this.salesTips(request);
            //         return;
            //     }
            // }
            // if(await this.getSearchListingUrlPrefix(url)){
            //     console.log(`➞ Search Listing Keywords:${url}`);
            //     if( !await this.checkUsedCount(searchListingKeywordsType)){
            //         await this.salesTips(request);
            //         return;
            //     }
            // }
            //注入用户token
            await this.injectToken(request);

            // let headers = request.headers();
            // headers['token'] = this.token;
            // delete headers['Cookie'];
            // delete headers['cookie'];

            // let options = {
            //     url:url,
            //     method:request.method(),
            //     rejectUnauthorized:false,
            //     requestCert:true
            // };



            // if(await this.needProxy(url)){
            //     options.proxy = `http://${config.PROXY.HOST}:${config.PROXY.PORT}`
            //     options.headers = headers;
            // }
            //
            // if(request.method() === 'POST'){
            //     options.body = request.postData();
            // }
            //
            // let isImage = request.resourceType() === 'image' || request.resourceType() === 'font';
            // console.log(`source type:${request.resourceType()}`);
            // if(isImage){
            //     options.encoding = null;
            // }
            //
            // console.log(`url:${url}\n options:${JSON.stringify(options)}`)
            //
            // myRequest(options,async (err,res,body) => {
            //     let responseData = {};
            //     if(err || res.statusCode !== 200){
            //         responseData.status = 500
            //     }else if(res.statusCode === 200){
            //         responseData.status = 200;
            //         responseData.headers = res.headers;
            //         if(isImage){
            //             responseData.body = Buffer.from(body);
            //         }else{
            //             responseData.body = body;
            //         }
            //     }
            //     request.respond(responseData);
            // })
        });
    }

    async needProxy(url){
        let isCurrent = utils.getUrlHostName(url).indexOf('junglescout') >= 0
        if(!isCurrent){
            return isCurrent;
        }
        //判断是否为静态资源
        return !utils.matchStaticSourceUrl(url);
    }

    async injectToken(request){
        let headers = request.headers();
        //注入用户token
        headers['token'] = this.token;
        delete headers['Cookie'];
        delete headers['cookie'];
        request.continue({
            headers:headers
        });
    }


    async checkUsedCount(type){
        //判断使用次数
        let data = await this.getCustomCount(type);
        if(!data){
            console.log(`获取服务器数据失败,无法查询使用次数`)
            return false;
        }
        if(data.usedCount >= data.totalCount){
            console.log(`使用次数已达上限 Type:[${type}] MaxCount:[${data.totalCount}] useCount:[${data.usedCount}]]`);
            return false;
        }
        return true;
    }

    async isOptionsResponse(response){
        let headers = response.headers();
        if(headers['X-custom-sing']){
            console.log(`custom-sing:${response.url()}`);
        }
        return (headers['content-type']) == undefined || headers['X-custom-sing'] === 'yes';
    }

    async isOptionRequest(request){
        console.log(`Method:${request.method()}`)
        return request.method() == 'OPTIONS';
    }

    async displaySearchButton(text = searchDefaultNotice){
        let divEl = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.SearchFormRow-sc-5tai76-1.iVvUfp > div.SearchWrapper-sc-5tai76-0.eZNwBb > button > div');
        if(!divEl){
            return;
        }

        await this.page.evaluate((els, value) => {
                els.innerHTML = value;
            },
            divEl,
            text
        );
    }


    async displayListingSearchButton(text = listingDefaultNotice){
        let divEl = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > section > div > div.MarketplaceAsinSelectorWrapper-sc-1v49vyh-4.fpLnzj > form > button > div');
        if(!divEl){
            return;
        }
        await this.page.evaluate((els, value) => {
                els.innerHTML = value;
            },
            divEl,
            text
        );
    }

    async displaySalesSearch(text = salesDefaultNotice){
        let divEl = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > section > div.SalesEstimator-sc-148qs1w-2.cTsHrX > div > form > div.Buttons-sc-1ot91hs-3.eDTOHJ > button.ButtonWrapper-sc-1vti96x-0.bXpqnz.StyledButton-sc-1ot91hs-4.bbhYJu > div');
        if(!divEl){
            return;
        }

        await this.page.evaluate((els, value) => {
                els.innerHTML = value;
            },
            divEl,
            text
        );
    }

    async displayListingKeywordsSearch(text = listingDefaultNotice){
        let divEl = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.filters.filters--keyword > div.FloatRight-szkeim-1.iTlsdl > button.ButtonWrapper-sc-1vti96x-0.bXpqnz > div');
        if(!divEl){
            return;
        }
        await this.page.evaluate((els, value) => {
                els.innerHTML = value;
            },
            divEl,
            text
        );
    }

    async displaySearchProductsSearch(text = listingDefaultNotice){
        let divEl = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > div > div.filters.filters--database > div.SearchSection-sc-1iuvgd5-4.eTmXrI > div > button.ButtonWrapper-sc-1vti96x-0.bXpqnz > div');
        if(!divEl){
            return;
        }
        await this.page.evaluate((els, value) => {
                els.innerHTML = value;
            },
            divEl,
            text
        );
    }

    async eventMonitor() {
        let buttonEl = await this.page.$('#app-content > div.RouterWrapper-irb435-0.hyDasN > section > div > div.MarketplaceAsinSelectorWrapper-sc-1v49vyh-4.fpLnzj > form > button');
        await this.page.evaluate(async (els, value) => {
            els.addEventListener('click',function () {
                console.log(`Button Click...`)
            })
        },buttonEl,undefined);
    }

    /**
     * 获取自定义功能已经使用的次数
     * @param type 类型 10(选品数据库) 20(时长搜索器)
     */
    async getCustomCount(type){
        return new Promise((resolve, reject) => {
            utils.post('/custom-time/getProductFunctionUseCount',JSON.stringify({
                productId:this.productId,
                type:type
            }),this.clientToken,(response) => {
                response = this.decode(JSON.stringify(response));
                response = JSON.parse(response);
                resolve(response.data);
            },(error) => {
                console.log(`Fetch Used Count Error:${JSON.stringify(data)}`);
                reject(error)
            })
        })
    }

    /**
     * 增加使用次数
     */
    async addUseCount(type){
        return new Promise((resolve, reject) => {
            utils.post('/custom-time/addProductFunctionUseCount',JSON.stringify({
                productId:this.productId,
                type:type
            }),this.clientToken,(response) => {
                response = this.decode(JSON.stringify(response));
                response = JSON.parse(response);
                resolve(response.data);
            },(error) => {
                console.log(`Fetch Used Count Error:${JSON.stringify(error)}`);
                reject(error)
            })
        })
    }

    async getSearchProductUrlPrefix(url){
        if(url.length <= searchProducts.length){
            return undefined;
        }
        let searchProductResponseUrl = url.substring(0,searchProducts.length);
        return searchProductResponseUrl.toString() === searchProducts;
    }

    async getSearchListingUrlPrefix(url){
        if(url.length <= searchListingKeywords.length){
            return undefined;
        }
        let searchListingResponseUrl = url.substring(0,searchListingKeywords.length);
        return searchListingResponseUrl.toString() === searchListingKeywords;
    }


}
Junglescout.single = null;
// module.exports = Junglescout;
export default Junglescout
